package com.monolith.jd.demo.common.resource;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;

/**
 * 2018/10/1 Create by 郭文梁
 * ImageData
 * Recommend of this class
 *
 * @author 郭文梁
 * @date 2018/10/1
 */
@Component
@Data
@Slf4j
public class ImageData {
    public static final String RESOURCE_PATH = "image/code.png";
    private String base64String;
    private byte[] bytes;

    @PostConstruct
    public void init() throws IOException {
        InputStream in = getClass().getClassLoader().getResourceAsStream(RESOURCE_PATH);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            if (in == null) {
                throw new IOException("resource not fond :" + RESOURCE_PATH);
            }
            IOUtils.copy(in, bos);
        } finally {
            if (in != null) {
                in.close();
            }
            bos.close();
        }
        bytes = bos.toByteArray();
        base64String = Base64.getEncoder().encodeToString(bytes);
    }
}
